using System;
using System.Collections;
using System.Runtime.CompilerServices;
using Awaiter;
using Nsb;
using Nsb.Classes;

namespace Yoshi.Classes
{
    /// <summary>
    /// Case insensitive record manager
    /// </summary>
    [IgnoreNamespace]
    public class RecordStore
    {
        public void GetRecord(Dictionary db, string key, string name, Await aw)
        {
            Inform.LogFn(Script.Literal("arguments"));
            if (Script.IsNullOrUndefined(db))
                throw new Exception(Exceptions.ArgumentNull);
            object records = db[key];
            if (Script.IsNullOrUndefined(records))
                throw new Exception(Exceptions.RecordNotExists);
            if (Script.IsNullOrUndefined(aw))
                throw new Exception(Exceptions.MissingAwaitDoneEr);
            Inform.Trace("RecordStore.GetRecord - EOM");
            aw.DoneWith("record", Type.GetField(records, name.ToLowerCase()));
        }

        public void PutRecord(Dictionary db, string key, string name, object record)
        {
            Inform.LogFn(Script.Literal("arguments"));
            if (Script.IsNullOrUndefined(db))
                throw new Exception(Exceptions.ArgumentNull);
            object records = db[key];
            if (Script.IsValue(records))
            {
                Type.SetField(records, name.ToLowerCase(), record);
            }
        }

        public void RenameRecord(Dictionary db, string key, string oldName, string newName)
        {
            oldName = oldName.ToLowerCase();
            newName = newName.ToLowerCase();
            Inform.LogFn(Script.Literal("arguments"));
            if (Script.IsNullOrUndefined(db))
                throw new Exception(Exceptions.ArgumentNull);
            object records = db[key];
            if (Script.IsValue(records))
            {
                if (Type.HasProperty(records, oldName))
                {
                    if (Type.HasProperty(records, newName))
                        throw new Exception(Exceptions.NewRecordExists);
                    object old = Type.GetField(records, oldName);
                    Type.SetField(records, newName, old);
                    Type.DeleteField(records, oldName);
                }
                else
                    throw new Exception(Exceptions.RecordNotExists);
            }
        }
    }
}